<template>
  <!-- 上传图片组件功能:
    1.基本上传
    2.图片回显
    3.图片删除
    4.进度条
    5.大图片预览
 -->
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <img
        v-if="value"
        v-imgerror
        :src="value"
        class="avatar"
        @click.stop.prevent="BigImgShow = true"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="loading" :percentage="percentage" />
    <!-- 删除按钮 -->
    <div v-if="value" class="del" @click="delImg">X</div>
    <!-- 大图片预览 -->
    <el-dialog :visible.sync="BigImgShow" title="图片预览">
      <div style="text-align: center">
        <img style="width: 60%" :src="value">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  // 密钥
  SecretId: 'AKIDHOGrBEzTgfNoysVrvjFUS9YgX7QSDiws',
  SecretKey: 'g5E6h02nHUP3RXN4VfX8SVHlyuZw2sRj'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      BigImgShow: false,
      percentage: 0,
      loading: false
      // imageUrl: ''
    }
  },
  methods: {
    // 图片上传前的设置上传图片的限制条件
    beforeUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 删除图片
    delImg() {
      this.$emit('input', '')
    },
    httpRequest(res) {
      // res.file就是我们需要传递给服务器的文件对象
      console.log(res)
      // 每次上传图片时进度条都要重置为0
      this.percentage = 0
      // 每次上传就显示进度条
      this.loading = true
      cos.putObject(
        {
          Bucket: 'hr78-1309565895' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-hongkong' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key:
            res.file.uid +
            '' /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度,可以实时获取上传的进度百分比
            this.percentage = progressData.percent * 100
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.loading = false
              }, 1000)
            }
            console.log(JSON.stringify(progressData))
          }
        },
        // 更改成箭头函数,让this指向vue实例对象,如果用函数里面又嵌套一个function函数那这个函数this指向为window
        (err, data) => {
          console.log(err || data)
          // this.imageUrl = 'http://' + data.Location
          this.$emit('input', 'http://' + data.Location)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadImg {
  position: relative;
  width: 178px;
  &:hover {
    .del {
      display: block;
    }
  }
  .del {
    display: none;
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
  }
}
</style>
